package net.wangds.auth.role.comp;

import net.wangds.auth.module.Role;
import net.wangds.auth.module.User;
import net.wangds.auth.role.entity.GeneralRoleEntity;
import net.wangds.auth.role.repo.rdbms.RoleJpaRepo;
import net.wangds.auth.role.repo.rdbms.RoleResRefJpaRepo;
import net.wangds.auth.user.entity.GeneralUserRoleRef;
import net.wangds.auth.user.repo.rdbms.UserRoleRefJpaRepo;
import net.wangds.data.DisableEnum;
import net.wangds.data.RemovedEnum;
import net.wangds.jdbc.comp.jdbc.JdbcComp;
import net.wangds.jpa.comp.AbstractRemovedComp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class GeneralRoleComp extends AbstractRemovedComp<GeneralRoleEntity> {

    @Autowired
    private UserRoleRefJpaRepo mmJpaUserRole;

    @Autowired
    private  JdbcComp mmJdbc;

    private final RoleJpaRepo mmJpaRole;

    protected GeneralRoleComp(RoleJpaRepo repo, RoleResRefJpaRepo refResRepo) {
        super(repo);
        mmJpaRole = repo;
    }

    public List<Role> listByRefUser(User usr) {
        List<String> idlist = mmJpaUserRole.findByUserId(usr.getId()).stream().map(c -> c.getRoleId()).collect(Collectors.toList());
        return mmJpaRole.findByIdIn(idlist);

    }

    public Page<Role> listUserUnrefRoles(User usr, PageRequest pr) {
        List<String> idlist = mmJpaUserRole.findByUserId(usr.getId()).stream().map(GeneralUserRoleRef::getRoleId).collect(Collectors.toList());
        if(idlist.isEmpty()){
            idlist.add("");
        }
        return mmJpaRole.findByIdNotInAndRemoved(idlist, RemovedEnum.NORMAL, pr);
    }

    @Override
    public Page<GeneralRoleEntity> findByKeywords(String keywords, Pageable paging) {
        String sql = "SELECT t1.* FROM cnpgmt.auth_role t1\n" +
                "where ( t1.role_code regexp ? or t1.role_name regexp ? or t1.role_desc regexp ? ) and t1.removed = 0";
        return mmJdbc.executeQuery(sql, new Object[]{keywords, keywords, keywords}, paging, GeneralRoleEntity.class);
    }
}
